package com.common.help.test15;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class NIOClient {
	
	private SocketChannel client;
	private Selector selector;
	private InetSocketAddress remote = new InetSocketAddress("localhost",8080);
	private ByteBuffer send = ByteBuffer.allocate(1024);
	private ByteBuffer recive = ByteBuffer.allocate(1024);
	public NIOClient() throws IOException{
		client = SocketChannel.open();
		client.configureBlocking(false);
		client.connect(remote);
		selector = Selector.open();
		client.register(selector, SelectionKey.OP_CONNECT);
		System.out.println("成功初始化端口,可以实现传输了");
	}

	public static void main(String[] args) throws IOException {
		new NIOClient().session();
	}

	private void session() throws IOException {
		if(client.isConnectionPending()){
			client.finishConnect();
			client.register(selector, SelectionKey.OP_WRITE);
			Scanner sc = new Scanner(System.in);
			while(sc.hasNext()){
				String what = sc.next();
				if("".equals(what)){
					continue;
				}else if(":".equals(what)){
					System.exit(0);
				}
				process(what);//执行key
				}
				
		}
	}

	private void process(String what) throws IOException {
		boolean flag = true;
		while(flag){
			int count = selector.select();
			if(count == 0){
				continue;
			}
			Set<SelectionKey> keys = selector.selectedKeys();
			Iterator<SelectionKey> iterator = keys.iterator();
			while(iterator.hasNext()){
				SelectionKey key = iterator.next();
				if(key.isWritable()){
					send.clear();
					send.put(what.getBytes());
					send.flip();
					client.write(send);
					client.register(selector, SelectionKey.OP_READ);
				}else if(key.isReadable()){
					recive.clear();
					int len = client.read(recive);
					//recive.flip();
					if(len > 0){
						System.out.println("信息返回"+new String(recive.array(),0,len));
					}
					client.register(selector, SelectionKey.OP_WRITE);
					flag = false;
				}
			}
		}
	}
}
